package com.tian.widget

import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import androidx.recyclerview.widget.RecyclerView

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2022/12/12 11:32
 */
class MaxHeightRecyclerView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    RecyclerView(context, attrs, defStyleAttr) {

    var maxHeight = 0
        set(value) {
            field = value
            requestLayout()
        }

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context) : this(context, null)

    init {
        initAttrs(context, attrs)
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        attrs?.let {
            val typeArray = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView)
            maxHeight = typeArray.getDimensionPixelSize(R.styleable.MaxHeightRecyclerView_maxHeight, 0)
            typeArray.recycle()
        }
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        if (maxHeight > 0) {
            val hSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
            super.onMeasure(widthSpec, hSpec)
        } else {
            super.onMeasure(widthSpec, heightSpec)
        }
    }

}